package com.zzzzzz.oms.driver;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.util.WebUtils;
import com.zzzzzz.core.datagrid.BaseData;
import com.zzzzzz.core.datagrid.BaseQueryForm;
import com.zzzzzz.utils.page.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zzzzzz.oms.GCS;
import com.zzzzzz.plugins.shiro.ShiroUtils;
import com.zzzzzz.plugins.poi.ExportExcel;
import com.zzzzzz.plugins.poi.ImportExcel;

/**
 * @author hing
 * @version 1.0.0
 */
@Controller
public class DriverWeb {

	@Resource
	public DriverService driverService;
	
	@Resource
	public DriverDao driverDao;

	// 打开界面
	@RequestMapping(value = "/driver/list", method = RequestMethod.GET)
	public String list() {
		return "oms/driver";
	}

	// 增加、修改
	@RequestMapping(value = "/driver/save", method = RequestMethod.POST)
	@ResponseBody
	public BaseData save(@RequestBody @Valid Driver driver, BindingResult bindingResult) throws Exception {
		if (bindingResult.hasErrors()) {
			return new BaseData(GCS.ERRCD_PARAM);
		}
		driverService.save(driver, ShiroUtils.findUser());
		return new BaseData("0");
	}
	
	// 停用数据
	@RequestMapping(value = "/driver/updStByIds", method = RequestMethod.POST)
	@ResponseBody
	public BaseData updStByIds(@RequestParam(value = "ids", required = true) List<Long> ids, @RequestParam(value = "st", required = true) Integer st) throws Exception {
		driverDao.updStByIds(ids, st, ShiroUtils.findUser());
		return new BaseData("0");
	}	  
	
	// 查找一条数据
	@RequestMapping(value = "/driver/id/{id}", method = RequestMethod.GET)
	@ResponseBody 
	public BaseData findById(@PathVariable Long id) {
		Driver driver = driverDao.findById(id);
		return new BaseData(driver, null);
	}
	
	// 动态查询
	@RequestMapping(value = "/driver/findListBy", method = RequestMethod.POST)
	@ResponseBody
	public BaseData findListBy(@RequestBody BaseQueryForm baseQueryForm) {
		Page page;
		List<Driver> list;
		BaseData baseData;
		if(baseQueryForm.getPageNb() == null && baseQueryForm.getPageSize() == null){
			list = driverDao.findListBy(null,baseQueryForm.getFfMap(),ShiroUtils.findUser());
			baseData=new BaseData(list, null);
		}else{
			page = baseQueryForm.getPage();
			list = driverDao.findListBy(page,baseQueryForm.getFfMap(),ShiroUtils.findUser());
			baseData = new BaseData(list, page.getTotal());
		}
		return baseData;
	}
	
	// 用于缓存
	@RequestMapping(value = "/driver/findAllBy", method = RequestMethod.POST)
	@ResponseBody
	public BaseData findAllBy() {
		List<Driver> list = driverDao.findAllBy(ShiroUtils.findUser());
		BaseData baseData=new BaseData(list, null);
		return baseData;
	}
	
	// 导入
	@RequestMapping(value = "/driver/import", method=RequestMethod.POST)
    public String importExcel(@RequestParam MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			if(StringUtils.isBlank(file.getOriginalFilename())){
				List<BaseData> list3 = new ArrayList<BaseData>();
				BaseData baseData = new BaseData();
				baseData.setErrMsg("您还没选择文件，请先选择需要导入的文件！");
				list3.add(baseData);
				redirectAttributes.addFlashAttribute("msg",list3);
			}else{
				ImportExcel importExcel = new ImportExcel(file, 1, 0);
				if(file.getOriginalFilename().contains("司机")){
					List<Driver> list = importExcel.getDataList(Driver.class);
					List<BaseData> list1 =driverService.batchAdd(list, ShiroUtils.findUser());
					redirectAttributes.addFlashAttribute("msg", list1);
				}else{
					List<BaseData> list2 = new ArrayList<BaseData>();
					BaseData baseData = new BaseData();
					baseData.setErrMsg("你导入模板有误，请重新选择模板导入。");
					list2.add(baseData);
					redirectAttributes.addFlashAttribute("msg", list2);
				}
			}			
		} catch (Exception e) {
			redirectAttributes.addFlashAttribute("msg", "导入数据保存失败。");
			logger.warn("importExcel", e);
		}
		return "redirect:/msg";
    }
    
	// 导出
	@RequestMapping(value = "/driver/export")
	 public String exportFileTemplate(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {	
			 Map<String, Object> params = WebUtils.getParametersStartingWith(request, null);
	          String fileName = "司机信息数据.xlsx";	            
	          List<Driver> list = driverDao.findListBy(null, params,ShiroUtils.findUser());
	    	  new ExportExcel("司机信息数据", Driver.class, 1).setDataList(list).write(response, fileName).dispose();
	    	  return null;
			} catch (Exception e) {
				redirectAttributes.addFlashAttribute("msg", "司机信息数据导出失败。");
				logger.warn("importFileTemplate", e);
			}
			return "redirect:/msg";
	   }
    
    private static final Logger logger = LoggerFactory.getLogger(DriverWeb.class);
}
